<?php
defined('BASEPATH') OR exit('No direct script access allowed');
define('AppKey', 'a3060dd7f245d0e2d8d8720ce18ebc89');
define('CAPTCHA_PATH_IMAGE', 'captcha');

class Welcome extends CI_Controller
{

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *        http://example.com/index.php/welcome
     *    - or -
     *        http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */

    public function login()
    {
        $this->load->view('login');
    }

    public function dologin()
    {
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $username = trim($this->input->post('txtUsername'));
            $password = trim($this->input->post('md5Password'));
            if (User::LogInUser($username, $password)) {
                $_SESSION["WANZ_USERNAME"] = $username;
                echo json_encode(['code' => 0, 'msg' => '登录成功！']);
            } else {
                echo json_encode(['code' => -100, 'msg' => '用户名或密码输入不正确！']);
            }
        }
    }

    public function set()
    {
        echo $cellname = chr(65 + 1) . (+3);
        die;
        $this->load->library('phpexcel/PHPExcel');
//        $this->load->library('phpexcel/PHPExcel/IOFactory');
//        require_once 'application/libraries/phpexcel/PHPExcel/IOFactory.php';
        $objPHPExcel = new PHPExcel();
        $data = [
            ['id' => 001, 'name' => 'jim001', 'age' => 29],
            ['id' => 002, 'name' => 'jim003', 'age' => 30]
        ];
        $uname = ['编号', '姓名', '年龄'];
//        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A2', '编号');
//        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B2', '姓名');
//        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C2', '年龄');
        $i = 0;
        foreach ($uname as $v) {
            if ($i < 26) {
                $cellname = chr(65 + $i) . (+2);
            } else {
                $cellname = "A" . chr(65 + $i - 26) . (+2);
            }
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellname, $v);
            $i++;
        }
        foreach ($data as $key => $value) {
            $key += 3;

            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $key, $value['id']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $key, $value['name']);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $key, $value['age']);
        }
        //设置表头
        $Sheet = $objPHPExcel->getActiveSheet();
        $Sheet->setTitle('JIM公司员工表');
        $Sheet->setCellValue('A1', "标题：员工统计表");
        $objPHPExcel->setActiveSheetIndex(0);
        //导出
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        header('pragma:public');
        $data["title"] = 'jim员工表';
        $file_load_name = iconv("utf-8", "gb2312", $data["title"]);
        header("Content-Disposition:attachment;filename=" . $file_load_name . ".xls");
        $objWriter->save('php://output');
        exit;

    }

    public function get_captcha()
    {
        try {
            $this->load->helper('captcha');
            $this->load->driver('cache');//引入缓存类
            $this->load->helper('cookie');
            $this->load->helper('string');
            $str = random_string('numeric', 4);
            $captcha_key = random_string('alnum', 6) . time();
            $vals = array(
                'word' => $str,
                'img_path' => './captcha/',
                'img_url' => '/captcha/',
                'img_width' => '150',
                'img_height' => '40',
                'expiration' => 300,
                'font_path' => '/resources/fonts/Duality.ttf'
            );
            $this->cache->save($captcha_key, $str, 10);
            set_cookie('captcha_key', $captcha_key, 10);
            $this->delCatchaImage();
            $cap = create_captcha($vals);
            echo $cap['image'];
        } catch (Exception $e) {
            show_error('500-redis服务未开启！');
        }
    }

    public function delCatchaImage()
    {
        if (file_exists(CAPTCHA_PATH_IMAGE)) {
            $imgs = glob(CAPTCHA_PATH_IMAGE . '/*');
            foreach ($imgs as $value) {
                unlink($value);
            }
        }

    }

    public function checkcaptcha()
    {
        $jsonRet = array();
        $txtCode = $this->input->post('txtCode');
        $this->load->helper('cookie');
        $this->load->driver('cache');//引入缓存类
        //读取存入验证码的键值
        $captcha_key = get_cookie('captcha_key');
        if (!$captcha_key) {
            $jsonRet["valid"] = false;
            exit(json_encode($jsonRet));
        }
        //从缓存中获取验证码
        $vcode = $this->cache->get($captcha_key);
        if (strtolower($txtCode) == strtolower($vcode)) {
            $jsonRet["valid"] = true;
        } else {
            $jsonRet["valid"] = false;
        }
        echo json_encode($jsonRet);
    }

    public function loginout()
    {
        $_SESSION["WANZ_USERNAME"] = null;
        redirect('/login');
    }
}
